package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;

public class RequestProcessor4 extends Thread{

    private Socket socket;

    private Mapper mapper;

    public RequestProcessor4(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            List<Host> hosts = mapper.getHosts();
            //循环读取host
            for (int i = 0; i < hosts.size(); i++) {
                Host host =  hosts.get(i);
                List<Context> contexts = host.getContexts();
                for (int j = 0; j < contexts.size(); j++) {
                    Context context =  contexts.get(j);
                    if(request.getUrl().contains(context.getPath())){ //匹配到对应的Wrapper
                        List<Wrapper> wrappers = context.getWrappers();
                        for (int k = 0; k < wrappers.size(); k++) {
                            Wrapper wrapper =  wrappers.get(k);
                            if (request.getUrl().equals("/"+context.getPath()+wrapper.getUrlPattern())) {
                                Servlet servlet = wrapper.getServlet();
                                servlet.service(request,response);
                                break;
                            }
                        }
                    }
                }

            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
